﻿using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using OS.Http.Models;

namespace OS.Http.Extention
{
    /// <summary>
    /// Http请求辅助类
    /// </summary>
    public static class RestExtention
    {
        private static HttpClient _client;

        /// <summary>
        /// 同步的请求方法
        /// </summary>
        /// <param name="request">Http请求</param>
        /// <param name="client">Http处理请求客户端</param>
        /// <returns></returns>
        public static Task<HttpResponseMessage> RestSend(this BaseHttpRequest request, HttpClient client = null)
        {
            return request.RestSend(HttpCompletionOption.ResponseContentRead, CancellationToken.None, client);
        }

        /// <summary>
        /// 同步的请求方法
        /// </summary>
        /// <param name="request">Http请求</param>
        /// <param name="completionOption">请求完成可选项</param>
        /// <param name="client">Http处理请求客户端</param>
        /// <returns></returns>
        public static Task<HttpResponseMessage> RestSend(this BaseHttpRequest request,
            HttpCompletionOption completionOption, HttpClient client = null)
        {
            return request.RestSend(completionOption, CancellationToken.None, client);
        }

        /// <summary>
        /// 同步的请求方法
        /// </summary>
        /// <param name="request">Http请求</param>
        /// <param name="completionOption">请求完成可选项</param>
        /// <param name="cancellationToken">请求取消Token</param>
        /// <param name="client">Http处理请求客户端</param>
        /// <returns></returns>
        public static Task<HttpResponseMessage> RestSend(this BaseHttpRequest request,
            HttpCompletionOption completionOption, CancellationToken cancellationToken, HttpClient client = null)
        {
            return (client ?? GetDefaultClient()).RestSend(request, completionOption, cancellationToken);
        }

        /// <summary>
        /// 配置请求处理客户端
        /// </summary>
        /// <returns></returns>
        private static HttpClient GetDefaultClient()
        {
            if (_client != null) return _client;
            return _client = new HttpClient();
        }
    }
}